package com.fg.pro.trade.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fg.pro.model.trade.dto.GmCustomerDto;
import com.fg.pro.trade.dao.TradeCustomerDao;
import com.fg.pro.trade.entity.TradeCustomer;
import com.fg.pro.trade.entity.TradeUnit;
import com.fg.pro.trade.service.TradeCustomerService;
import com.fg.pro.trade.utils.GmHttpUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.fg.pro.trade.utils.GmRequestUrl.*;

/**
 * 客户(TradeCustomer)表服务实现类
 *
 * @author makejava
 * @since 2025-08-21 10:05:02
 */
@Service("tradeCustomerService")
public class TradeCustomerServiceImpl extends ServiceImpl<TradeCustomerDao, TradeCustomer> implements TradeCustomerService {

    @Autowired
    GmHttpUtils gmHttpUtils;
    @Autowired
    RedissonClient redissonClient;

    @Override
    public PageInfo getPage(Integer pageNum, Integer pageSize, String customerName) {
        PageHelper.startPage(pageNum, pageSize);
        List<TradeCustomer> list = query().like(StrUtil.isNotBlank(customerName),"customer_name",customerName).list();
        PageInfo<TradeCustomer> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public boolean refresh(Date date) {
        RLock lock = redissonClient.getLock(REDIS_LOCK_URL+GM_CUSTOMER_URL);
        boolean tryLock = lock.tryLock();
        if(!tryLock){
            return false;
        }
        try {
            return refreshTradeCustomerByLock(date);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    private boolean refreshTradeCustomerByLock(Date date) throws InterruptedException {
        GmCustomerDto.GmCustomerReponse gmCustomerReponse = gmHttpUtils.httpPostByToken(GM_CUSTOMER_URL, new GmCustomerDto().new GmCustomerRequest().gmCustomerRequest(999), GmCustomerDto.GmCustomerReponse.class);
        LinkedList<TradeCustomer> newList = new LinkedList<>();
        for (GmCustomerDto.GmCustomerReponse.CustomerData customerData : gmCustomerReponse.getCustomers()) {
            TradeCustomer tradeCustomer = new TradeCustomer();
            tradeCustomer.setId(customerData.customer_id);
            tradeCustomer.setCustomerParentId(customerData.getParent_id());
            tradeCustomer.setCreateTime(new Date(customerData.getCreate_time()));
            tradeCustomer.setUpdateTime(new Date(customerData.getUpdate_time()));
            tradeCustomer.setCustomerStatus(customerData.getStatus());
            tradeCustomer.setCustomerGroupId(customerData.getGroup_id());
            tradeCustomer.setCustomerName(customerData.getName());
            tradeCustomer.setCustomerCode(customerData.getCustomized_code());
            tradeCustomer.setCustomerType(customerData.getType());
            tradeCustomer.setCustomerWhitelist(customerData.getIs_in_whitelist()?1:0);
            tradeCustomer.setCustomerReviewed(customerData.getIs_reviewed()?1:0);
            tradeCustomer.setCustomerLev(customerData.getLevel());
            tradeCustomer.setCustomerDimension(customerData.getSettlement().getDate_dimension());
            tradeCustomer.setCustomerPeriod(customerData.getSettlement().getSettle_period());
            tradeCustomer.setCustomerCreditType(customerData.getCredit_type());
            tradeCustomer.setCustomerCreditStartDay(customerData.getSettlement().getWeekly_or_monthly_credit_start_day());
            tradeCustomer.setCustomerCreditSettleDay(customerData.getSettlement().getWeekly_or_monthly_credit_settle_day());
            tradeCustomer.setCustomerCreditDeleyDays(customerData.getSettlement().getWeekly_or_monthly_credit_deley_days());
            tradeCustomer.setCustomerUnpayAmount(customerData.getSettlement().getUnpay_amount());
            tradeCustomer.setCustomerAvailableAmount(customerData.getSettlement().getAvailable_amount());
            tradeCustomer.setCustomerInvoiceCompanyName(customerData.getSettlement().getChina_vat_invoice().getCompany_name());
            tradeCustomer.setCustomerInvoiceContactName(customerData.getSettlement().getChina_vat_invoice().getFinancial_contact_name());
            tradeCustomer.setCustomerInvoiceContactPhone(customerData.getSettlement().getChina_vat_invoice().getFinancial_contact_phone());
            tradeCustomer.setCustomerSet(customerData.getSettlement_method());
            tradeCustomer.setCustomerPurchaseRule(customerData.getHave_purchase_rule());
            tradeCustomer.setCustomerWarehouseId(customerData.getWarehouse_id());
            tradeCustomer.setCustomerVip(customerData.getIs_vip_customer());
            tradeCustomer.setCustomerDiscountRate(customerData.getDiscount_rate());
            newList.add(tradeCustomer);
        }
        boolean saved = saveOrUpdateBatch(newList);
        return saved;
    }

    @Override
    public Map<String, Long> getIdAndCode() {
        Map<String, Long> map = query().list().stream().collect(Collectors.toMap(TradeCustomer::getCustomerCode, TradeCustomer::getId));
        return map;
    }
}

